package org.biubiu0002.baiblog.core.async.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.core.async.event.PostShareEvent;
import org.biubiu0002.baiblog.core.config.RabbitMqConfig;
import org.biubiu0002.baiblog.core.service.FeedService;
import org.biubiu0002.baiblog.core.service.ShareService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-30 23:31
 **/
@RabbitListener(queues = RabbitMqConfig.POST_SHARE_QUEUE)
@Component
@Slf4j
public class PostShareListener {

    @Resource
    private ShareService shareService;

    @Resource
    private FeedService feedService;

    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(msg));
            log.info("收到发布推文消息: {}", msg);
            PostShareEvent postShareEvent = JSON.parseObject(msg, PostShareEvent.class);
            String userUid = postShareEvent.getUserUid();
            String shareId = postShareEvent.getShareId();
            Long createTime = postShareEvent.getCreateTime();
            shareService.insertIntoLatestBoard(shareId);
            log.info("推文加入到最新发布榜单: {}", msg);
            //发布到粉丝信箱中
            log.info("推文发布到粉丝信箱中:{}",msg);
            feedService.sendToFans(userUid,shareId,createTime);


            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            if (Boolean.TRUE.equals(message.getMessageProperties().isRedelivered())) {
                log.error("[消费拒绝]:{}",message,e);
                channel.basicReject(deliveryTag, false);
            } else {
                log.warn("[消费重试]:{}",message,e);
                channel.basicNack(deliveryTag, false, true);
            }
        }


    }


}
